package com.cardcaptorsakura.security;

import io.jsonwebtoken.*;
import io.jsonwebtoken.security.Keys;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.function.Function;

/**
 * JWT工具类
 * 提供JWT令牌的生成、验证和解析功能
 */
@Slf4j
@Component
public class JwtUtil {

    @Value("${app.jwt.secret:cardcaptor-sakura-secret-key-for-jwt-token-generation}")
    private String jwtSecret;

    @Value("${app.jwt.expiration:86400000}") // 24小时
    private long jwtExpirationMs;

    @Value("${app.jwt.refresh-expiration:604800000}") // 7天
    private long refreshExpirationMs;

    @Value("${app.jwt.issuer:CardcaptorSakura}")
    private String jwtIssuer;

    private SecretKey getSigningKey() {
        byte[] keyBytes = jwtSecret.getBytes();
        return Keys.hmacShaKeyFor(keyBytes);
    }

    /**
     * 生成访问令牌
     */
    public String generateAccessToken(String userId, String username, List<String> roles) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("roles", roles);
        claims.put("type", "access");
        
        return createToken(claims, username, jwtExpirationMs);
    }

    /**
     * 生成刷新令牌
     */
    public String generateRefreshToken(String userId, String username) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("username", username);
        claims.put("type", "refresh");
        
        return createToken(claims, username, refreshExpirationMs);
    }

    /**
     * 生成人格切换令牌
     */
    public String generatePersonaSwitchToken(String userId, String fromPersonaId, String toPersonaId) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("fromPersonaId", fromPersonaId);
        claims.put("toPersonaId", toPersonaId);
        claims.put("type", "persona_switch");
        claims.put("switchTime", LocalDateTime.now().toString());
        
        // 人格切换令牌有效期较短，30分钟
        return createToken(claims, userId, 1800000);
    }

    /**
     * 创建令牌
     */
    private String createToken(Map<String, Object> claims, String subject, long expirationMs) {
        Date now = new Date();
        Date expiryDate = new Date(now.getTime() + expirationMs);
        
        return Jwts.builder()
                .setClaims(claims)
                .setSubject(subject)
                .setIssuer(jwtIssuer)
                .setIssuedAt(now)
                .setExpiration(expiryDate)
                .signWith(getSigningKey(), SignatureAlgorithm.HS512)
                .compact();
    }

    /**
     * 从令牌中获取用户名
     */
    public String getUsernameFromToken(String token) {
        return getClaimFromToken(token, Claims::getSubject);
    }

    /**
     * 从令牌中获取用户ID
     */
    public String getUserIdFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("userId", String.class));
    }

    /**
     * 从令牌中获取角色列表
     */
    @SuppressWarnings("unchecked")
    public List<String> getRolesFromToken(String token) {
        return getClaimFromToken(token, claims -> {
            Object roles = claims.get("roles");
            if (roles instanceof List) {
                return (List<String>) roles;
            }
            return Collections.emptyList();
        });
    }

    /**
     * 从令牌中获取令牌类型
     */
    public String getTokenTypeFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("type", String.class));
    }

    /**
     * 从令牌中获取过期时间
     */
    public Date getExpirationDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getExpiration);
    }

    /**
     * 从令牌中获取签发时间
     */
    public Date getIssuedAtDateFromToken(String token) {
        return getClaimFromToken(token, Claims::getIssuedAt);
    }

    /**
     * 从令牌中获取指定声明
     */
    public <T> T getClaimFromToken(String token, Function<Claims, T> claimsResolver) {
        final Claims claims = getAllClaimsFromToken(token);
        return claimsResolver.apply(claims);
    }

    /**
     * 从令牌中获取所有声明
     */
    private Claims getAllClaimsFromToken(String token) {
        try {
            return Jwts.parserBuilder()
                    .setSigningKey(getSigningKey())
                    .build()
                    .parseClaimsJws(token)
                    .getBody();
        } catch (JwtException e) {
            log.error("Error parsing JWT token", e);
            throw e;
        }
    }

    /**
     * 检查令牌是否过期
     */
    public Boolean isTokenExpired(String token) {
        try {
            final Date expiration = getExpirationDateFromToken(token);
            return expiration.before(new Date());
        } catch (Exception e) {
            log.error("Error checking token expiration", e);
            return true;
        }
    }

    /**
     * 验证令牌
     */
    public Boolean validateToken(String token, UserDetails userDetails) {
        try {
            final String username = getUsernameFromToken(token);
            return (username.equals(userDetails.getUsername()) && !isTokenExpired(token));
        } catch (Exception e) {
            log.error("Error validating token", e);
            return false;
        }
    }

    /**
     * 验证令牌（不需要UserDetails）
     */
    public Boolean validateToken(String token) {
        try {
            getAllClaimsFromToken(token);
            return !isTokenExpired(token);
        } catch (Exception e) {
            log.error("Error validating token", e);
            return false;
        }
    }

    /**
     * 验证访问令牌
     */
    public Boolean validateAccessToken(String token) {
        try {
            String tokenType = getTokenTypeFromToken(token);
            return "access".equals(tokenType) && validateToken(token);
        } catch (Exception e) {
            log.error("Error validating access token", e);
            return false;
        }
    }

    /**
     * 验证刷新令牌
     */
    public Boolean validateRefreshToken(String token) {
        try {
            String tokenType = getTokenTypeFromToken(token);
            return "refresh".equals(tokenType) && validateToken(token);
        } catch (Exception e) {
            log.error("Error validating refresh token", e);
            return false;
        }
    }

    /**
     * 验证人格切换令牌
     */
    public Boolean validatePersonaSwitchToken(String token) {
        try {
            String tokenType = getTokenTypeFromToken(token);
            return "persona_switch".equals(tokenType) && validateToken(token);
        } catch (Exception e) {
            log.error("Error validating persona switch token", e);
            return false;
        }
    }

    /**
     * 刷新访问令牌
     */
    public String refreshAccessToken(String refreshToken) {
        try {
            if (!validateRefreshToken(refreshToken)) {
                throw new IllegalArgumentException("Invalid refresh token");
            }
            
            String userId = getUserIdFromToken(refreshToken);
            String username = getUsernameFromToken(refreshToken);
            
            // 这里应该从数据库获取最新的角色信息
            // 为了简化，这里使用默认角色
            List<String> roles = Arrays.asList("USER");
            
            return generateAccessToken(userId, username, roles);
        } catch (Exception e) {
            log.error("Error refreshing access token", e);
            throw new RuntimeException("Failed to refresh access token", e);
        }
    }

    /**
     * 获取令牌剩余有效时间（秒）
     */
    public long getTokenRemainingTime(String token) {
        try {
            Date expiration = getExpirationDateFromToken(token);
            Date now = new Date();
            return Math.max(0, (expiration.getTime() - now.getTime()) / 1000);
        } catch (Exception e) {
            log.error("Error getting token remaining time", e);
            return 0;
        }
    }

    /**
     * 检查令牌是否即将过期（30分钟内）
     */
    public Boolean isTokenExpiringSoon(String token) {
        try {
            long remainingTime = getTokenRemainingTime(token);
            return remainingTime > 0 && remainingTime < 1800; // 30分钟
        } catch (Exception e) {
            log.error("Error checking if token is expiring soon", e);
            return false;
        }
    }

    /**
     * 从人格切换令牌中获取源人格ID
     */
    public String getFromPersonaIdFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("fromPersonaId", String.class));
    }

    /**
     * 从人格切换令牌中获取目标人格ID
     */
    public String getToPersonaIdFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("toPersonaId", String.class));
    }

    /**
     * 从人格切换令牌中获取切换时间
     */
    public LocalDateTime getSwitchTimeFromToken(String token) {
        String switchTimeStr = getClaimFromToken(token, claims -> claims.get("switchTime", String.class));
        try {
            return LocalDateTime.parse(switchTimeStr);
        } catch (Exception e) {
            log.error("Error parsing switch time from token", e);
            return null;
        }
    }

    /**
     * 生成API密钥令牌
     */
    public String generateApiKeyToken(String userId, String apiKeyId, List<String> permissions) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", userId);
        claims.put("apiKeyId", apiKeyId);
        claims.put("permissions", permissions);
        claims.put("type", "api_key");
        
        // API密钥令牌有效期较长，30天
        return createToken(claims, userId, 2592000000L);
    }

    /**
     * 验证API密钥令牌
     */
    public Boolean validateApiKeyToken(String token) {
        try {
            String tokenType = getTokenTypeFromToken(token);
            return "api_key".equals(tokenType) && validateToken(token);
        } catch (Exception e) {
            log.error("Error validating API key token", e);
            return false;
        }
    }

    /**
     * 从API密钥令牌中获取权限列表
     */
    @SuppressWarnings("unchecked")
    public List<String> getPermissionsFromToken(String token) {
        return getClaimFromToken(token, claims -> {
            Object permissions = claims.get("permissions");
            if (permissions instanceof List) {
                return (List<String>) permissions;
            }
            return Collections.emptyList();
        });
    }

    /**
     * 从API密钥令牌中获取API密钥ID
     */
    public String getApiKeyIdFromToken(String token) {
        return getClaimFromToken(token, claims -> claims.get("apiKeyId", String.class));
    }

    /**
     * 解析令牌头部信息
     */
    public Map<String, Object> parseTokenHeader(String token) {
        try {
            String[] chunks = token.split("\\.");
            if (chunks.length != 3) {
                throw new IllegalArgumentException("Invalid JWT token format");
            }
            
            Base64.Decoder decoder = Base64.getUrlDecoder();
            String header = new String(decoder.decode(chunks[0]));
            
            // 这里应该使用JSON解析库，为了简化使用Map
            Map<String, Object> headerMap = new HashMap<>();
            headerMap.put("raw", header);
            
            return headerMap;
        } catch (Exception e) {
            log.error("Error parsing token header", e);
            return Collections.emptyMap();
        }
    }

    /**
     * 获取令牌签名算法
     */
    public String getTokenAlgorithm(String token) {
        try {
            Map<String, Object> header = parseTokenHeader(token);
            return (String) header.get("alg");
        } catch (Exception e) {
            log.error("Error getting token algorithm", e);
            return null;
        }
    }

    /**
     * 检查令牌是否被篡改
     */
    public Boolean isTokenTampered(String token) {
        try {
            getAllClaimsFromToken(token);
            return false; // 如果能成功解析，说明没有被篡改
        } catch (SignatureException e) {
            log.warn("Token signature verification failed", e);
            return true;
        } catch (Exception e) {
            log.error("Error checking token tampering", e);
            return true;
        }
    }

    /**
     * 生成令牌指纹
     */
    public String generateTokenFingerprint(String token) {
        try {
            // 使用令牌的哈希值作为指纹
            return Integer.toHexString(token.hashCode());
        } catch (Exception e) {
            log.error("Error generating token fingerprint", e);
            return null;
        }
    }
}